<template>
  <div class="form-text">
    <input
      type="number"
      :value="value"
      @compositionstart="compositionstart"
      @compositionend="compositionend"
      @input="inputEvent"
      @focus="handlerInputFocus"
      @blur="handlerInputBlur"
      :maxlength="field.maxlength ? field.maxlength : maxlength"
      :id="`form_${field.fieldName}`"
      autocomplete="off"
      :disabled="disabled"
    />
  </div>
</template>

<script>
import FormMixin from '@src/component/form/mixin/form';
import { FORM_FIELD_TEXT_MAX_LENGTH } from '@src/model/const/Number.ts';
import { genPlaceholder } from '../../util';

const IS_NUMBER_REG = /^\d{1,}$/;
export default {
  name: 'FormEstimatedMileageLabel',
  mixins: [FormMixin],
  props: {
    value: {
      type: [String, Number],
      default: '',
    },
    isOnlyNumber: {
      type: Boolean,
      default: false,
    },
    isNotInputZh: {
      type: Boolean,
      default: false,
    },
    placeholder: {
      type: String,
    },
  },
  data() {
    return {
      // 是否是输入中文
      $isInputZh: false,
      maxlength: FORM_FIELD_TEXT_MAX_LENGTH,
      placeholderText: '',
    };
  },
  watch: {
    field: {
      handler(newValue) {
        this.placeholderText = genPlaceholder(this.field);
      },
      immediate: true,
    },
  },
  methods: {
    SetChange() {
      this.value = Number(this.value)?.toFixed(2) || this.value;
    },
    /* 输入文字之前 */
    compositionstart(event) {
      this.$data.$isInputZh = true;
    },
    /* 输入文字之后 */
    compositionend(event) {
      if (!this.isNotInputZh) {
        this.$data.$isInputZh = false;
      }

      this.input(event);
    },
    inputEvent(event) {
      const eventValue = event.target.value;

      if (this.isOnlyNumber && !IS_NUMBER_REG.test(eventValue)) {
        event.target.value = this.value;
      }

      if (this.isOnlyNumber && !eventValue) {
        event.target.value = eventValue;
      }

      if (eventValue && eventValue.length > 8) {
        event.target.value = eventValue.slice(0, 8);
      }

      // 如果是在中文输入 return
      if (this.$data.$isInputZh) return;

      this.input(event);
    },
    handlerInputFocus() {
      this.$emit('focus');
    },
    handlerInputBlur() {
      this.$emit('blur', 'input');
    },
  },
  computed: {
    /**
     * @description 不允许修改
     * 1.有默认值
     * 
     * 里程没有默认值，所以只用isNotModify判断即可
     */
    disabled() {
      let field = this.field;
      return (
        field.disabled ||
        (field.setting &&
          field.setting.defaultValueConfig &&
          !!field.setting.defaultValueConfig.isNotModify)
      );
    },
  },
};
</script>
<style lang="scss">
.form-text {
  width: 100%;
//  display: flex;

  input {
    width: 100%;
    &:disabled {
      -webkit-text-fill-color: #bfbfbf;
      border-color: #d9d9d9;
      background-color: #f5f5f5 !important;
      &:hover {
        border-color: #d9d9d9;
      }
    }
  }
}
</style>
